package ldk.util.slipview

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import java.lang.ref.WeakReference


/**
 *
 * The RootView can slip back return
 * Created by ldkxingzhe@163.com on 2017/6/20.
 */
class SlipRootView(context: Context?, attrs: AttributeSet? = null)
    : SlipView(context, attrs) {

    companion object{
        val TAG = "SlipRootView"

        fun preActivityCloseExistAnimation(activity: Activity){
            val decorView = activity.window.decorView
            val animator = ViewCompat.animate(decorView).translationX(-decorView.width/ 5.0f)
            animator.duration = 250
            animator.start()
        }
    }

    var eatBack: Boolean
    var previousActivity: ()->Activity? = {null}

    private var tmpPreviousActivity: WeakReference<Activity?>? = null

    init {
        val array = context!!.obtainStyledAttributes(attrs, R.styleable.SlipRootView)
        eatBack = array.getBoolean(R.styleable.SlipRootView_eatBack, true)
        array.recycle()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        postDelayed({
            previousActivity.invoke()?.window?.decorView?.translationX = 0f
            if (DEBUG){
                Log.v(TAG, "close previous activity")
            }
        }, 500)
    }

    private fun getActivity(): Activity{
        var context = context
        while (context is ContextWrapper){
            if (context is Activity){
                return context
            }
            context = context.baseContext
        }
        throw IllegalStateException("Your View must attached on activity")
    }

    fun getStatusBarHeight(): Int{
        var result = 0
        val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0){
            result = context.resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    override fun finishPageWithAnimation(){
        super.finishPageWithAnimation()
        tmpPreviousActivity = WeakReference(previousActivity.invoke())
    }

    override fun onOffsetChanged(offset: Float) {
        super.onOffsetChanged(offset)
        var activity = previousActivity.invoke()
        if (activity == null){
            activity = tmpPreviousActivity?.get()
        }
        if (activity != null){
            val decorView = activity.window?.decorView
            if (decorView != null){
                val realOffset = if (isRevertOffset()) offset - 1 else offset
                val otherOffset = (realOffset - 1) * 0.5f
                if (isHorizontal()){
                    decorView.translationX = width * otherOffset
                }else{
                    decorView.translationY = height * otherOffset
                }
            }
        }
    }

    override fun onPageFinished() {
        super.onPageFinished()
        finishActivity()
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && eatBack){
            finishPageWithAnimation()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun finishActivity() {
        val activity = getActivity()
        activity.finish()
        activity.overridePendingTransition(0, 0)
    }
}